import time

from cbu.pyhod.files import add_input_file
from cbu.pyhod.jobs import add_job, get_job_status, is_job_ended
from cbu.pyhod.session import start_session

from LCAClassifier.web.config import config


def wait_for_job(job_id):
    status = get_job_status(job_id)
    while not is_job_ended(job_id):
        print "job: " + job_id + " status is : " + status
        time.sleep(1)
        status = get_job_status(job_id)
    print "job: " + job_id + " exited with status :" + status


def main(db_name, input_files):

    session_id = start_session()
    print "Sesssion created with id: " + session_id

    # --== Pre-processing  ==--
    all_fasta = ''
    for filename in input_files:

        # Change to read uploaded file (Svenn)
        file_content = open(filename, "r").read()
        add_input_file(session_id, filename, file_content)
        all_fasta += file_content

    # Checking max. sequences
    # TODO: move to form validation
    if all_fasta.count('>') > config.SEQ_LIMIT:
        # Throw exception?
        error_descr = ("Too many sequences submitted! (Max. allowed = %s)" %
                       config.SEQ_LIMIT)
        print error_descr
        return error_descr

    catFile = "All.fasta"
    add_input_file(session_id, catFile, all_fasta)

    # --== MEGABLAST job submission ==--
    blastJobIDs = []
    xmlFiles = []

    for inputfile in input_files:

        xmlOut = inputfile[:inputfile.find(".")] + ".xml"
        xmlFiles.append(xmlOut)

        parameters = ("-i %s -o %s -m7 -b100 -v100 -d %s -a 2" %
                      (inputfile, xmlOut, db_name))

        blastJobIDs.append(add_job(session_id, "megablast", parameters,
                                   [inputfile], [xmlOut], [], True))

    # --== Classify job submission ==--

    # Add these options with the following defaults (Svenn):
    minscore = 155  # Minimum bitscore max 1000
    lca_range = 2  # LCA-range (bitscore)

    xmlIn = str(xmlFiles).replace(",", "").replace("[", "").replace("]", "")
    args = ("-v -o -a -i %s -s %s -r %s %s" %
            (catFile, minscore, lca_range, xmlIn))

    outFiles = ["All_Composition.txt"]
    for xmlfile in xmlFiles:
        assignedFastaOut = xmlfile.replace(".xml", "_Assignments.fasta")
        outFiles.append(assignedFastaOut)

        compoOut = xmlfile.replace(".xml", "_Composition.txt")
        outFiles.append(compoOut)

    lca_job_id = add_job(session_id=session_id,
                         executable_name="lcaclassifier_classify",
                         parameters=args,
                         prerequisite_job_ids=blastJobIDs,
                         input_file_names=xmlFiles + [catFile],
                         output_file_names=outFiles,
                         stage_output_files=True)

    wait_for_job(lca_job_id)

    # Present links to files, or email, or zip...

if __name__ == "__main__":
    main('silvamod',
         ['SnotDNA_F_Good.fa'])
